package cj.web.portal.controllers;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import cj.web.admin.constants.Constants;
import cj.web.kly.domain.News;
import cj.web.login.controllers.BaseController;
import cj.web.portal.service.ColumnsNewsService;

/**
 * 全文检索
 * @author Administrator
 *
 */
@Path("search")
public class SearchController extends BaseController {
	
	private static String NOT_SEARCH = "NOT_SEARCH";
	
	private static Logger logger = Logger.getLogger(SearchController.class.getName());
	
	@Autowired
	private ColumnsNewsService columnsNewsService;
	
	/**
	 * 检索页面
	 * @return
	 * @throws Exception 
	 */
	@Get("searchListPage")
	public String searchListPage(Model model,@Param("keywords") String keywords,HttpServletRequest request) throws Exception {
		model.add("keywords",keywords);
		return "/views/portal/search.vm";
	}
	
	/**
	 * 请求方法
	 * @param columnsId
	 * @param start
	 * @param length
	 * @return
	 * @throws ParseException
	 */
	@Post("getNewsList")
	public String queryList(@Param("keywords") String keywords,
			@Param("start") int start,@Param("length") int length,Invocation inv) throws ParseException {
		
		ServletContext context = inv.getServletContext();  
        HashMap dictionaryInfoMap = (HashMap)context.getAttribute("dictionaryInfoMap");
		Map configRep = (Map) dictionaryInfoMap.get("configRep");
		String not_in_news_columnsid=configRep.get(NOT_SEARCH).toString();//不显示新闻
		
		//提取中文字符
		String reg = "[^\u4e00-\u9fa5]";  
		
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		Map rep = columnsNewsService.querySearchList(not_in_news_columnsid,keywords, start*length, length);
		List<News> objs = (List<News>) rep.get("newslis");
		for(News obj:objs){
			String content = obj.getContent().replaceAll(reg, "");
			obj.setContent(content.substring(0, content.length()>200?200:content.length())+"...");
		}
		int size = (int) rep.get("size");
		jo.put("list", objs);
		jo.put("totalCount", size);
		return "@"+jo.toString();
	}
}